let passwordInput = document.getElementById("password");
let confirmPasswordInput = document.getElementById("confirmPassword");
let passwordError = document.getElementById("passwordError");
let registerBtn = document.getElementById("formRegister");

// 获取头像相关元素
let avatarInput = document.getElementById('avatar');
let avatarPreview = document.getElementById('avatarPreview');
let previewImage = document.getElementById('previewImage');

// 当确认密码输入框失去焦点时，检查两次密码是否一致
confirmPasswordInput.addEventListener("blur", function () {
    let password = passwordInput.value;
    let confirmPassword = this.value;

    if (password !== confirmPassword) {
        passwordError.textContent = "两次输入的密码不一致!";
        passwordError.style.display = "block";
        registerBtn.disabled = true;
    } else {
        passwordError.textContent = "";
        passwordError.style.display = "none";
        registerBtn.disabled = false;
    }
});

// 当密码输入框内容改变时，清除错误信息
passwordInput.addEventListener("input", function () {
    passwordError.textContent = "";
    passwordError.style.display = "none";
    registerBtn.disabled = false;
});

// 当确认密码输入框内容改变时，清除错误信息
confirmPasswordInput.addEventListener("input", function () {
    passwordError.textContent = "";
    passwordError.style.display = "none";
    registerBtn.disabled = false;
});
// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    // 获取头像相关元素
    let avatarInput = document.getElementById('avatar');

    if (avatarInput) {
        // 绑听文件选择事件
        avatarInput.addEventListener('change', function(e) {
            console.log('文件选择事件触发');
            alert('上传头像');

            const file = e.target.files[0];
            if (file) {
                console.log('选择了文件:', file.name);
                // 显示文件名
                document.getElementById('fileName').style.display = 'block';
                document.getElementById('fileNameText').textContent = file.name;

                // 创建文件读取器用于预览
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewImage.src = e.target.result;
                    avatarPreview.style.display = 'block';
                }
                reader.readAsDataURL(file);

                // 上传文件到服务器
                uploadAvatar(file);
            } else {
                document.getElementById('fileName').style.display = 'none';
                avatarPreview.style.display = 'none';
            }
        });
    } else {
        console.error('无法找到id为avatar的元素');
    }
});

function uploadAvatar(file) {
    console.log('开始上传头像:', file.name);

    // 创建FormData对象，用于发送文件
    const formData = new FormData();
    formData.append('avatar', file);

    // 创建XMLHttpRequest对象
    const xhr = new XMLHttpRequest();

    // 设置请求的URL和方法
    xhr.open('POST', '/user/uploadAvatar', true);

    // 添加错误处理
    xhr.onerror = function() {
        console.error('上传请求失败');
        alert('上传请求失败，请检查网络连接');
    };

    // 监听上传进度
    xhr.upload.addEventListener('progress', function(e) {
        if (e.lengthComputable) {
            const percentComplete = (e.loaded / e.total) * 100;
            console.log('上传进度:', percentComplete.toFixed(2) + '%');
        }
    });

    // 监听响应
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            console.log('上传响应状态:', xhr.status);

            if (xhr.status === 200) {
                try {
                    // 解析服务器返回的JSON响应
                    const response = JSON.parse(xhr.responseText);

                    if (response.url) {
                        // 上传成功，将返回的URL存储在隐藏字段中
                        if (!document.getElementById('avatarUrl')) {
                            const hiddenInput = document.createElement('input');
                            hiddenInput.type = 'hidden';
                            hiddenInput.id = 'avatarUrl';
                            hiddenInput.name = 'avatarUrl';
                            document.querySelector('.right-panel').appendChild(hiddenInput);
                        }
                        document.getElementById('avatarUrl').value = response.url;

                        // 显示成功提示
                        alert('头像上传成功！');
                    } else {
                        alert('头像上传失败，请重试');
                    }
                } catch (e) {
                    console.error('解析响应失败:', e);
                    alert('上传失败，请重试');
                }
            } else {
                console.error('上传失败，状态码:', xhr.status);
                alert('上传失败，请重试');
            }
        }
    };

    // 发送上传请求
    console.log('发送上传请求...');
    xhr.send(formData);
}


registerBtn.addEventListener("submit", function (event) {
    event.preventDefault();
    // 获取表单数据
    let username = document.getElementsByName("username")[0].value;
    let password = document.getElementsByName("password")[0].value;
    let avatarUrl = document.getElementById("avatarUrl") ? document.getElementById("avatarUrl").value : "";

    // 构造表单数据
    const formData = new FormData();
    formData.append("username", username);
    formData.append("password", password);
    if (avatarUrl) {
        formData.append("avatarUrl", avatarUrl);
    }
    alert('注册用户')
    // 发送注册请求
    const xhr = new XMLHttpRequest();
    xhr.open("POST", "/user/register", true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                // 注册成功，跳转到登录页面
                window.location.href = "/login";
            } else {
                // 注册失败
                alert('注册失败，请重试!');
            }
        }
    };
    xhr.send(formData);
});
